// 评论管理模块 - 包含评论显示、提交、回复等功能

// 评论相关全局变量
let replyToCommentId = null;

// ========== 评论数徽章增强（动态） ==========
(function() {
    // 简单缓存，避免重复请求
    const commentCountCache = Object.create(null);

    function appendBadge(btn, count) {
        if (!btn || btn.querySelector('.comment-count-badge')) return;
        const span = document.createElement('span');
        span.className = 'badge bg-secondary ms-1 comment-count-badge';
        span.textContent = String(typeof count === 'number' ? count : 0);
        btn.appendChild(span);
    }

    function extractContentIdFromOnclick(onclick) {
        if (!onclick || typeof onclick !== 'string') return null;
        // 兼容单引号或双引号: showComments('123') / showComments("123")
        const m = onclick.match(/showComments\((['"])([^'"]+)\1\)/);
        return m ? m[2] : null;
    }

    async function fetchCount(contentId) {
        if (!contentId) return 0;
        if (Object.prototype.hasOwnProperty.call(commentCountCache, contentId)) {
            return commentCountCache[contentId];
        }
        try {
            const resp = await fetch(`/api/content/${contentId}`);
            const data = await resp.json();
            const count = (data && typeof data.comment_count !== 'undefined') ? data.comment_count : 0;
            commentCountCache[contentId] = count;
            return count;
        } catch (e) {
            return 0;
        }
    }

    async function updateCommentBadges() {
        const buttons = document.querySelectorAll('button[onclick^="showComments("]');
        for (const btn of buttons) {
            if (btn.querySelector('.comment-count-badge')) continue;
            const cid = extractContentIdFromOnclick(btn.getAttribute('onclick'));
            const count = await fetchCount(cid);
            appendBadge(btn, count);
        }
    }

    // 初次运行
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            updateCommentBadges().catch(() => {});
        });
    } else {
        updateCommentBadges().catch(() => {});
    }

    // 监听DOM变化，列表/搜索渲染后自动补齐徽章（去抖）
    let timer = null;
    const obs = new MutationObserver(() => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => updateCommentBadges().catch(() => {}), 120);
    });
    obs.observe(document.body, { childList: true, subtree: true });
})();
// ========== 评论数徽章增强 End ==========

// ========== 评论显示和操作函数 ==========

// 显示评论
function showComments(contentId) {
    currentContentId = contentId;
    const modal = new bootstrap.Modal(document.getElementById('commentsModal'));
    modal.show();
    
    // 重置评论容器
    document.getElementById('commentsContainer').innerHTML = `
        <div class="text-center">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
        </div>
    `;
    
    // 重置回复状态
    resetReplyForm();
    
    // 加载评论
    loadComments(contentId);
}

// 加载评论
function loadComments(contentId) {
    fetch(`/api/content/${contentId}/comments`)
        .then(response => response.json())
        .then(data => {
            displayComments(data.comments);
        })
        .catch(error => {
            console.error('Error loading comments:', error);
            document.getElementById('commentsContainer').innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    加载评论失败
                </div>
            `;
        });
}

// 显示评论列表
function displayComments(comments) {
    const container = document.getElementById('commentsContainer');
    
    if (!comments || comments.length === 0) {
        container.innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>
                暂无评论，来发表第一个评论吧！
            </div>
        `;
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 创建评论树结构
    const commentMap = {};
    const rootComments = [];
    
    // 第一步：将所有评论放入映射
    comments.forEach(comment => {
        comment.replies = [];
        commentMap[comment.id] = comment;
    });
    
    // 第二步：构建树结构
    comments.forEach(comment => {
        if (comment.parent_id) {
            // 这是一个回复，添加到父评论的回复列表中
            const parentComment = commentMap[comment.parent_id];
            if (parentComment) {
                parentComment.replies.push(comment);
            } else {
                // 如果找不到父评论，作为根评论处理
                rootComments.push(comment);
            }
        } else {
            // 这是一个根评论
            rootComments.push(comment);
        }
    });
    
    // 渲染评论树
    rootComments.forEach(comment => {
        container.appendChild(createCommentElement(comment, 0));
    });
}

// 创建评论元素
function createCommentElement(comment, level) {
    const commentDiv = document.createElement('div');
    commentDiv.className = 'comment-item mb-3 p-3 border rounded';
    commentDiv.id = `comment-${comment.id}`;
    
    // 设置缩进和边框样式
    if (level > 0) {
        commentDiv.style.marginLeft = `${level * 30}px`;
        commentDiv.style.borderLeft = '3px solid #3b82f6';
    }
    
    // 评论头部
    const headerDiv = document.createElement('div');
    headerDiv.className = 'd-flex justify-content-between align-items-center mb-2';
    
    const userDiv = document.createElement('div');
    
    // 如果是回复，添加回复标记
    if (comment.parent_id) {
        const replyBadge = document.createElement('span');
        replyBadge.className = 'badge bg-light text-secondary me-2';
        replyBadge.textContent = '回复';
        userDiv.appendChild(replyBadge);
    }
    
    // 用户名（可点击）
    const usernameLink = document.createElement('a');
    usernameLink.href = 'javascript:void(0)';
    usernameLink.className = 'user-link';
    usernameLink.textContent = comment.username;
    usernameLink.onclick = function() {
        showUserProfile(comment.user_id);
    };
    
    const usernameStrong = document.createElement('strong');
    usernameStrong.appendChild(usernameLink);
    userDiv.appendChild(usernameStrong);
    
    // 时间戳
    const timeSmall = document.createElement('small');
    timeSmall.className = 'text-muted';
    timeSmall.textContent = formatDate(comment.created_at);
    
    headerDiv.appendChild(userDiv);
    headerDiv.appendChild(timeSmall);
    
    // 评论内容
    const commentP = document.createElement('p');
    commentP.className = 'mb-2';
    commentP.textContent = comment.comment;
    
    // 回复按钮
    const actionsDiv = document.createElement('div');
    actionsDiv.className = 'd-flex justify-content-end';
    
    const replyButton = document.createElement('button');
    replyButton.className = 'btn btn-sm btn-link reply-button';
    replyButton.innerHTML = '<i class="bi bi-reply me-1"></i>回复';
    replyButton.onclick = function() {
        // 设置回复状态
        document.getElementById('commentText').placeholder = `回复 @${comment.username}...`;
        document.getElementById('commentForm').dataset.parentId = comment.id;
        document.getElementById('cancelReplyBtn').classList.remove('d-none');
        document.getElementById('commentText').focus();
    };
    
    actionsDiv.appendChild(replyButton);
    
    // 组装评论元素
    commentDiv.appendChild(headerDiv);
    commentDiv.appendChild(commentP);
    commentDiv.appendChild(actionsDiv);
    
    // 递归添加回复
    if (comment.replies && comment.replies.length > 0) {
        comment.replies.forEach(reply => {
            commentDiv.appendChild(createCommentElement(reply, level + 1));
        });
    }
    
    return commentDiv;
}

// ========== 评论表单处理函数 ==========

// 重置回复表单
function resetReplyForm() {
    document.getElementById('commentText').placeholder = '输入您的评论...';
    document.getElementById('commentForm').dataset.parentId = '';
    document.getElementById('cancelReplyBtn').classList.add('d-none');
}

// 处理评论提交
function handleCommentSubmit(e) {
    e.preventDefault();
    
    if (!currentUser) {
        alert('请先登录后再发表评论');
        return;
    }
    
    const commentText = document.getElementById('commentText').value.trim();
    if (!commentText) {
        alert('请输入评论内容');
        return;
    }
    
    // 获取父评论ID（如果有）
    const parentId = document.getElementById('commentForm').dataset.parentId || null;
    
    fetch(`/api/content/${currentContentId}/comments`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
            comment: commentText,
            parent_id: parentId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('commentText').value = '';
            resetReplyForm();
            loadComments(currentContentId);
        } else {
            alert(data.error || '发表评论失败');
        }
    })
    .catch(error => {
        console.error('Error submitting comment:', error);
        alert('发表评论失败，请重试');
    });
}

// ========== 评论搜索相关函数 ==========

// 生成评论搜索结果HTML
function generateCommentResultHtml(comment) {
    return `
        <div class="content-item comment-result fade-in">
            <div class="row">
                <div class="col-2">
                    <div class="content-type-icon content-type-comment">
                        <i class="bi bi-chat-quote"></i>
                    </div>
                </div>
                <div class="col-10">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <strong>评论</strong>
                        <div class="d-flex align-items-center">
                            <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${comment.user_id})" class="user-link">${comment.username}</a></small>
                            <span class="timestamp me-2">${formatDate(comment.created_at)}</span>
                            <button class="btn btn-sm btn-outline-primary" onclick="showComments('${comment.content_id}')">
                                <i class="bi bi-chat-dots"></i>
                            </button>
                        </div>
                    </div>
                    <div class="content-preview">
                        <div class="comment-text mb-2">
                            ${comment.comment}
                        </div>
                        <div class="content-reference mt-2">
                            <small class="text-muted">
                                <i class="bi bi-arrow-return-right me-1"></i>
                                评论于: <a href="javascript:void(0)" onclick="showContentInModal('${comment.content_id}')" class="content-link">${comment.content_title || '无标题内容'}</a>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// ========== 事件监听器绑定 ==========

document.addEventListener('DOMContentLoaded', function() {
    // 评论表单提交
    document.getElementById('commentForm').addEventListener('submit', handleCommentSubmit);
    
    // 取消回复按钮
    const cancelReplyBtn = document.getElementById('cancelReplyBtn');
    if (cancelReplyBtn) {
        cancelReplyBtn.addEventListener('click', resetReplyForm);
    }
});